//
//  NvCompileAndSaveViewController.m
//  NvSellerShow
//
//  Created by Meicam on 2017/2/16.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvCompileAndSaveViewController.h"
#import "NvFilmViewController.h"
#import "MsVideoUploadModel.h"
#import "UAProgressView.h"
#import "NvDraftManager.h"
#import "NvUploadManager.h"
#import <AssetsLibrary/AssetsLibrary.h>


@interface NvCompileAndSaveViewController ()<UITextFieldDelegate>{
    NSTimer *_playbackProgressTimer;
    CGFloat offset;
    
    BOOL isShow;//是否显示控制栏标志
    CGFloat fileSize;

}

//popup tableview data source

@property (weak, nonatomic) IBOutlet UIView *palyControlView;

@property (strong, nonatomic) UIButton *saveDraftBtn;
@property (strong, nonatomic) UIButton *backBtn;
@property (nonatomic, strong) NSMutableArray *fileArray;

@property (nonatomic, strong) NSString *localVideoPath;
@property (nonatomic, strong) PHAssetCollection *targetCollection;

@property (strong, nonatomic) UIView *uploadView;
@property (strong, nonatomic) UILabel *stateLabel;
@property (strong, nonatomic) UAProgressView *progressView;

@property (assign, nonatomic) NvCompileSaveMode saveMode;

@end

@implementation NvCompileAndSaveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.liveWindow.fillMode = NvsLiveWindowFillModePreserveAspectFit;
    
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:self.liveWindow];
    self.streamingContext.delegate = self;
    self.localVideoPath = [self getLocalVideoPath];
    self.targetCollection = [self createdAssetCollection];
    
    self.curLabel.text = @"00:00";
    self.endLabel.text = [Utils stringWithTime:self.timeline.duration/NS_TIME_BASE];
    self.nvSlider.value = 0.0f;
    [self.streamingContext seekTimeline:self.timeline timestamp:0 videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
    isShow = YES;
    fileSize = 0.0;
    [self initFileArray];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addKeyBoardNotification];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)initFileArray {
    self.fileArray = [NSMutableArray array];
    for (NSDictionary *videoDict in [self readDataFromFiles]) {
        [self.fileArray addObject:videoDict];
    }
}

- (void)setupUI {
    self.view.backgroundColor = UIColorHexRGB(@"#F5F5F5");
    if(self.editmode != NvSSVideoCreateScaleHorizontal){
        self.liveWindow16x9AspectConstraint.active = NO;
        [self.view addConstraint:self.liveWindow1x1AspectConstraint];
    }
    [self initNavigationBarView];
    [self initUploadView];
    //input TextField
    self.textField.delegate = self;
}

#pragma mark 输入框代理及键盘弹窗事件
//是否含有表情
- (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

- (BOOL)textFieldShouldReturn:(UITextField *)aTextfield {
    [aTextfield resignFirstResponder];
    return YES;
}
- (void)addKeyBoardNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:self.textField];
}

- (BOOL)isSpecialCharacterWith:(NSString *)textString {
    NSString *legalString = @"^[a-zA-Z0-9_ \u4e00-\u9fa5]{0,}$";
    NSPredicate *legalPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",legalString];
    return [legalPre evaluateWithObject:textString];
}
#pragma mark-- UITextFieldDelegate

- (void)textFieldEditChanged:(NSNotification *)info {
    UITextField *textField = (UITextField *)info.object;
    NSString *toBeString = textField.text;
    if ([self stringContainsEmoji:toBeString]) {
        NSLog(@"这是emoji表情");
//        self.textField.text = [self.textField.text substringToIndex:(self.textField.text.length - 2)];
    } else {
        NSLog(@"不是emoji表情");
    }
    if (![self isSpecialCharacterWith:toBeString]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [textField resignFirstResponder];
            [Utils showMessageAlertWithTitle:@"输入失败" message:@"禁止输入特殊字符"];
            self.textField.text = [self.textField.text substringToIndex:(self.textField.text.length - 1)];
        });
        return;
    }
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > NV_MAX_TEXTLENGTH) {
                [Utils showMessageAlertWithTitle:@"输入失败" message:@"最大长度为50"];
                return;
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > NV_MAX_TEXTLENGTH) {
            [Utils showMessageAlertWithTitle:@"输入失败" message:@"最大长度为50"];
            return;
        }
    }
}

- (void)_keyboardWillShow:(NSNotification *)info {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat upOffset = self.inputView.bottom_LL - (self.view.frame.size.height - kbHeight) + 10;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    
    //将视图上移计算好的偏移
    if(upOffset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.topLayoutConstraint.constant -= upOffset;
        }];
    }
}
- (void)_keyboardWillHide:(NSNotification *)info
{
    // 键盘动画时间
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.topLayoutConstraint.constant = 10 ;
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initNavigationBarView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [self.backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(doBackEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backBtn];
    
    self.saveDraftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.saveDraftBtn.frame = CGRectMake(self.view.width_LL-60, 0, 60, 44);
    [self.saveDraftBtn setTitle:@"存草稿" forState:UIControlStateNormal];
    [self.saveDraftBtn setTitleColor:UIColorHexRGB(@"#3F80FF") forState:UIControlStateNormal];
    [self.saveDraftBtn addTarget:self action:@selector(saveDraft:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.saveDraftBtn];
    
    self.title = @"发布";
}

- (void) startSeekTimeline {
    if (_isPlaying) {
        _isPlaying = false;
        [_playbackProgressTimer invalidate];
        _isPlaying = false;
        [_playBtn setImage:[UIImage imageFromBundle:@"player_play"] forState:UIControlStateNormal];
    }
    [self.streamingContext seekTimeline:self.timeline timestamp:lround(self.nvSlider.value * self.timeline.duration) videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}


- (IBAction)sliderValueChanged:(id)sender {
    [self updateLabel];
    [self startSeekTimeline];
    
}

- (IBAction)saveToLocal:(id)sender {
    [self.streamingContext stop];
    self.saveMode = NvCompileSaveModeLocal;
    [self checkVideoDuration];
}

- (IBAction)saveAndUpload:(id)sender {
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相册权限" message:@"设置-隐私-照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self.streamingContext stop];
    NSString *curNet = [self currentNetWork];
    if ([curNet isEqualToString:@"NO-WIFI"]) {
        [Utils showMessageAlertWithTitle:@"上传失败" message:@"当前无网络"];
        return;
    } else if ([curNet isEqualToString:@"WIFI"]) {
        self.saveMode = NvCompileSaveModeUpload;
        [self checkVideoDuration];
    } else {
        [Utils showConfirmAlertWithTitle:@"流量提醒" message:@"您正在使用移动网络,是否上传" yesTitle:@"确定" yesAction:^{
            self.saveMode = NvCompileSaveModeUpload;
            [self checkVideoDuration];
        }cancelTitle:@"取消" cancelAction:nil];
    }
}

- (void)checkVideoDuration {
    if ((self.timeline.duration/NS_TIME_BASE) > 90 || (self.timeline.duration/NS_TIME_BASE) < 12) {
        [Utils showMessageAlertWithTitle:@"保存失败" message:@"视频长度需在12-90s内"];
    } else {
        [self checkVideoName];
    }
}

- (void)checkVideoName {
    if (self.textField.text.length <= 0) {
        [Utils showConfirmAlertWithTitle:@"温馨提醒" message:@"视频尚未命名,是否保存" yesTitle:@"确定" yesAction:^{
            [self doPackVideoAndSaveLocal];
        } cancelTitle:@"取消" cancelAction:^{
            return ;
        }];
    }  else {
        [self doPackVideoAndSaveLocal];
    }
}

- (void)handleProgressTimer:(NSTimer *)timer {
    self.nvSlider.value = self.nvSlider.maximumValue * [self.streamingContext getTimelineCurrentPosition:self.timeline] / self.timeline.duration;
    [self updateLabel];
}

- (void) updateLabel {
    self.curLabel.text = [Utils stringWithTime: self.nvSlider.value * self.timeline.duration/NS_TIME_BASE];
}

- (IBAction)play:(id)sender {
    if(_isPlaying)
    {
        _isPlaying = false;
        [_playBtn setImage:[UIImage imageFromBundle:@"player_play"] forState:UIControlStateNormal];
        [self.streamingContext stop];
        [_playbackProgressTimer invalidate];
    }
    else
    {
        _isPlaying = true;
        [_playBtn setImage:[UIImage imageFromBundle:@"player_stop"] forState:UIControlStateNormal];
        int64_t duration = _timeline.duration;
        if (self.timeline.duration - _nvSlider.value * duration < 500000) {
            self.nvSlider.value = 0;
            [self updateLabel];
        }
        [self.streamingContext playbackTimeline:self.timeline startTime:_nvSlider.value * duration endTime:self.timeline.duration videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
        NSTimeInterval timeInterval = 0.1;
        _playbackProgressTimer = [NSTimer timerWithTimeInterval:timeInterval target:self selector:@selector(handleProgressTimer:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_playbackProgressTimer forMode:NSRunLoopCommonModes];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self clear];
}


- (void)clear {
    [self.streamingContext stop];
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:nil];
    self.streamingContext.delegate = nil;
}

- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    if(timeline == self.timeline) {
        _isPlaying = false;
        [_playBtn setImage:[UIImage imageFromBundle:@"player_play"] forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
        self.nvSlider.value = self.nvSlider.maximumValue;
        [self updateLabel];
    }
}

- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    if(timeline == self.timeline) {
        _isPlaying = false;
        [_playBtn setImage:[UIImage imageFromBundle:@"player_play"] forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
    }
}


- (void)saveDraft:(id)sender {
    //cause the draft is aleady saved before going into this page,so just return to home page
    if (self.textField.text.length <= 0) {
        [Utils showConfirmAlertWithTitle:@"温馨提示" message:@"视频尚未命名,将由系统随机生成" yesTitle:@"确定" yesAction:^{
            [self doSaveDraftWork];
            [Utils showMessageAlertWithTitle:@"保存成功" message:@"存草稿成功"];
        } cancelTitle:@"取消" cancelAction:NULL];
    } else {
        [self doSaveDraftWork];
        [Utils showMessageAlertWithTitle:@"保存成功" message:@"存草稿成功"];
    }

}

- (void)doSaveDraftWork {
    NSString *fileName;
    if (self.textField.text.length <= 0) {
        fileName = [Utils getTimeAndRandom];
    } else {
        fileName = self.textField.text;
    }
    UIImage *coverImage = [self.streamingContext grabImageFromTimeline:self.timeline timestamp:(self.nvSlider.value * self.timeline.duration) proxyScale:nil];
    NSMutableDictionary *draftDict = [NSMutableDictionary dictionaryWithDictionary:self.draftDict];
    [draftDict setValue:UIImagePNGRepresentation(coverImage) forKey:@"coverImage"];
    [draftDict setValue:[Utils stringWithTime:self.timeline.duration/NS_TIME_BASE] forKeyPath:@"videoDuration"];
    [draftDict setValue:fileName forKey:@"fileName"];
    dispatch_async(dispatch_get_main_queue(), ^{
        [NvDraftManager addDraft:draftDict];
    });
}

- (void)doBackEvent:(id)sender {
    [self clear];
    [self.navigationController popViewControllerAnimated:YES];
}
//hide the keyboard when click other area
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    
    if (![touch.view isKindOfClass: [UITextField class]] || ![touch.view isKindOfClass: [UITextView class]]) {
        [self.view endEditing:YES];
    }
}

//MARK: Dealloc
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"打包页面释放");
}

- (NSArray *)readDataFromFiles {
    NSString *assetPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //得到完整的文件名
    NSString *localFileName=[assetPath stringByAppendingPathComponent:@"MsLocalVideoInfo.plist"];
    return [NSArray arrayWithContentsOfFile:localFileName];
}

//做本地打包及保存
- (void)doPackVideoAndSaveLocal {
    [_playbackProgressTimer invalidate];
    [self doSaveDraftWork];
    self.view.userInteractionEnabled = NO;
    self.backBtn.userInteractionEnabled = NO;
    self.saveDraftBtn.userInteractionEnabled = NO;
    self.uploadView.hidden = NO;
    self.stateLabel.text = @"开始生成视频";
    [self.progressView setProgress:0 animated:YES];
    [self.streamingContext compileTimeline:self.timeline startTime:0 endTime:self.timeline.duration outputFilePath:self.localVideoPath videoResolutionGrade:NvsCompileVideoResolutionGrade1080 videoBitrateGrade:NvsCompileBitrateGradeHigh flags:0];
}

- (void)doWriteToFileWork {
    UIImage *coverImage = [self.streamingContext grabImageFromTimeline:self.timeline timestamp:(self.nvSlider.value * self.timeline.duration) proxyScale:nil];
    NSString *fileName;
    if (self.textField.text.length <= 0) {
        fileName = [Utils getTimeAndRandom];
    } else {
        fileName = self.textField.text;
    }
    NSString *assetPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //得到完整的文件名
    NSString *localFileName=[assetPath stringByAppendingPathComponent:@"MsLocalVideoInfo.plist"];
    MsVideoUploadModel *model = [[MsVideoUploadModel alloc]init];
    model.themeUuid = self.modelUUID;
    model.fileName = fileName;
    model.filePath = [NSURL fileURLWithPath:[self getAllVideoAsset]];
    model.fileDuration = [Utils stringWithTime:self.timeline.duration/NS_TIME_BASE];
    model.corverImage = coverImage;
    model.scale = self.editmode;
    model.fileSize = fileSize;
    NSMutableDictionary *dict = [model changeToDictionary];
    [self.fileArray addObject:dict];
    //这里判断需不需要上传
    if ([self.fileArray writeToFile:localFileName atomically:YES]) {
        if (self.saveMode == NvCompileSaveModeLocal) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.uploadView setHidden:YES];
                self.view.userInteractionEnabled = YES;
                self.backBtn.userInteractionEnabled = YES;
                self.saveDraftBtn.userInteractionEnabled = YES;
                for(UIViewController *controller in self.navigationController.viewControllers) {
                    if([controller isKindOfClass:[MsViewController class]]){
                        MsViewController *owr = (MsViewController *)controller;
                        [self.navigationController popToViewController:owr animated:YES];
                    }
                }
            });
        } else {
            [self addUploadNotificationWith:model];
        }
    };
}



#pragma mark - implement NvsStreamingContextDelegate
- (void)deleteFile:(NSString *) path {
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

- (void)deleteCompiledFilesAfterFailedOrCancel {
    [self deleteFile:self.localVideoPath];
}

- (void)didCompileFailed:(NvsTimeline *)timeline {
    [self deleteCompiledFilesAfterFailedOrCancel];
    [Utils showMessageAlertWithTitle:@"提示" message:@"保存失败"];
    [self.uploadView setHidden:YES];
    self.view.userInteractionEnabled = YES;
    self.backBtn.userInteractionEnabled = YES;
    self.saveDraftBtn.userInteractionEnabled = YES;
    [self.uploadView setHidden:YES];
}

- (void)didCompileFinished:(NvsTimeline *)timeline {
    self.stateLabel.text = @"打包成功,正在存入";
    fileSize = [[NSFileManager defaultManager]attributesOfItemAtPath:self.localVideoPath error:nil].fileSize*1.0/(1024*1024);
    [self exportVideoPath:self.localVideoPath];
    
}

- (void)didCompileProgress:(NvsTimeline *)timeline progress:(int)progress {
    if (self.saveMode == NvCompileSaveModeLocal) {
         [self.progressView setProgress:progress/100.0 animated:YES];
    } else {
        [self.progressView setProgress:progress / 200.0 animated:YES];
    }
   
}

- (NSString *)getDocumentPath {
    NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    return documentsDirectory;
}

- (NSString *)getCompileVideoPath {
    return [[self getDocumentPath] stringByAppendingPathComponent:NS_COMPILE_VIDEO_PATH];
}

- (NSString *)getLocalVideoPath {
    return [[self getCompileVideoPath] stringByAppendingFormat:@"/video%@.mov",[Utils getTimeAndRandom]];
}

- (void)initUploadView {
    self.uploadView = [[UIView alloc]initWithFrame:CGRectMake(self.view.centerX_LL - 100, self.view.centerY_LL-100-64, 200, 200)];
    self.uploadView.layer.borderWidth = 2.0;
    self.uploadView.layer.borderColor = [UIColor orangeColor].CGColor;
    self.uploadView.layer.cornerRadius = 60;
    self.uploadView.backgroundColor = [UIColor lightGrayColor];
    
    self.progressView = [[UAProgressView alloc]initWithFrame:CGRectMake(40, 10, 120, 120)];
    self.progressView.tintColor = UIColorHexRGB(@"#5bc2e5");
    self.progressView.borderWidth = 1.0;
    self.progressView.lineWidth = 2.0;
    self.progressView.fillOnTouch = YES;
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80.0, 30.0)];
    textLabel.font = [UIFont systemFontOfSize:24];
    
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.textColor = UIColorHexRGB(@"#5bc2e5");
    textLabel.backgroundColor = [UIColor clearColor];
    self.progressView.centralView = textLabel;
    
    self.progressView.progressChangedBlock = ^(UAProgressView *progressView, CGFloat progress){
        [(UILabel *)progressView.centralView setText:[NSString stringWithFormat:@"%2.0f%%", progress * 100]];
    };
    [self.uploadView addSubview:self.progressView];
    
    self.stateLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.progressView.bottom_LL+10, 200, 30)];
    self.stateLabel.textColor = [UIColor whiteColor];
    self.stateLabel.text = @"打包视频中,请稍后...";
    self.stateLabel.textAlignment = NSTextAlignmentCenter;
    self.stateLabel.font = [UIFont systemFontOfSize:14];
    [self.uploadView addSubview:self.stateLabel];
    
    [self.view addSubview:self.uploadView];
    [self.uploadView setHidden:YES];
}

// upload notification

- (void)addUploadNotificationWith:(MsVideoUploadModel *)model {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.stateLabel.text = @"正在上传...";
    });
    NvUploadManager *manager = [NvUploadManager defaultManager];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [manager uploadTaskfromFile:[model changeToDictionary] progressValue:^(NSProgress *progress) {
            NSLog(@"当前收到的上传进度:%lli--%lli",progress.completedUnitCount,progress.totalUnitCount);
            dispatch_async(dispatch_get_main_queue(), ^{
                CGFloat curProgress = progress.completedUnitCount *0.5/progress.totalUnitCount+0.5;
                [self.progressView setProgress:curProgress animated:YES];
            });
        } completionHandler:^(NSError *error) {
            if (error != nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Utils showMessageAlertWithTitle:@"上传失败" message:@""];
                    [self.uploadView setHidden:YES];
                    self.view.userInteractionEnabled = YES;
                    self.backBtn.userInteractionEnabled = YES;
                    self.saveDraftBtn.userInteractionEnabled = YES;
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.uploadView setHidden:YES];
                    self.view.userInteractionEnabled = YES;
                    self.backBtn.userInteractionEnabled = YES;
                    self.saveDraftBtn.userInteractionEnabled = YES;

                    [Utils showConfirmAlertWithTitle:@"上传成功" message:@"" firstActionTitle:@"继续拍摄" firstAction:^{
                        for(UIViewController *controller in self.navigationController.viewControllers) {
                            if([controller isKindOfClass:[MsViewController class]]){
                                MsViewController *owr = (MsViewController *)controller;
                                [self.navigationController popToViewController:owr animated:YES];
                            }
                        }
                    } secondActionTitle:@"选择视频" secondAction:^{
                        for(UIViewController *controller in self.navigationController.viewControllers) {
                            if([controller isKindOfClass:[MsViewController class]]){
                                MsViewController *owr = (MsViewController *)controller;
                                NSInteger index = [self.navigationController.viewControllers indexOfObject:owr];
                                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:index-1] animated:YES];
                            }
                        }
                    }];
                });
            }
        }];
    });
}

//保存到本地相册
- (void)exportVideoPath:(NSString *)videoPath{
    
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相册权限" message:@"设置-隐私-照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{

        PHAssetChangeRequest *changeAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:videoPath]];

        PHAssetCollectionChangeRequest *changeCollectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.targetCollection];

        PHObjectPlaceholder *assetPlaceholder = [changeAssetRequest placeholderForCreatedAsset];

        [changeCollectionRequest addAssets:@[assetPlaceholder]];

    } completionHandler:^(BOOL success,NSError * _Nullable error) {
        [self deleteFile:self.localVideoPath];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self doWriteToFileWork];
            });
        } else {
        }
    }];
}

- (PHAssetCollection *)createdAssetCollection {
    // 从已存在相簿中查找这个应用对应的相簿
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *assetCollection in assetCollections) {
        if ([assetCollection.localizedTitle isEqualToString:NS_COMPILED_VIDEO_ASSETS_GROUP_NAME]) {
            return assetCollection;
        }
    }
    // 没有找到对应的相簿, 得创建新的相簿
    // 错误信息
    NSError *error = nil;
    // PHAssetCollection的标识, 利用这个标识可以找到对应的PHAssetCollection对象(相簿对象)
    __block NSString *assetCollectionLocalIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 创建相簿的请求
        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:NS_COMPILED_VIDEO_ASSETS_GROUP_NAME].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];

    // 如果有错误信息
    if (error) return nil;
    // 获得刚才创建的相簿
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

- (NSString *)getAllVideoAsset {
    __block NSString *localVideoPath;
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    PHAssetCollection *assetCollection = [self createdAssetCollection];
    // 是否按创建时间排序
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeVideo];
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    // 获取所有视频对象
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
    // 最后一个存入的对象
    PHAsset *asset = [result lastObject];
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        AVURLAsset *urlAsset = (AVURLAsset *)asset;
        localVideoPath = urlAsset.URL.path;
        dispatch_semaphore_signal(sem);
    }];
    //等待信号
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    return localVideoPath;
}

- (NSString *)currentNetWork {
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    switch (type) {
        case 1:
            return @"2G";
            break;
        case 2:
            return @"3G";
        case 3:
            return @"4G";
        case 5:
            return @"WIFI";
        default:
            return @"NO-WIFI";//代表未知网络
            break;
    }
}
@end
